<template>
  <div id="monaco-editor" ref="monacoEditorRef" />
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import { onMounted, ref, toRaw, watch } from "vue";

/**
 * 定义组件属性类型
 */
interface Props {
  code: string;
  language: string;
  handleChange: (v: string) => void;
  readonly: boolean;
}

/**
 * 给组件指定初始值
 */
const props = withDefaults(defineProps<Props>(), {
  code: () => "",
  language: () => "java",
  handleChange: (v: string) => {},
  readonly: () => false,
});

const monacoEditorRef = ref();
const monacoEditor = ref();

/**
 * 监听编程语言的变化
 */
watch(
  () => props.language,
  () => {
    if (monacoEditor.value) {
      monaco.editor.setModelLanguage(
        toRaw(monacoEditor.value).getModel(),
        props.language
      );
    }
  }
);

/**
 * 创建 monacoEditor 对象
 */
onMounted(() => {
  if (!monacoEditorRef.value) return;
  monacoEditor.value = monaco.editor.create(monacoEditorRef.value, {
    value: props.code,
    language: props.language,
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      enabled: true,
    },
    readOnly: props.readonly,
    theme: "vs-dark",
  });

  /**
   * 监听代码内容变化
   */
  monacoEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(monacoEditor.value).getValue());
  });
});
</script>

<style scoped>
/*代码编辑器样式*/
#monaco-editor {
  min-height: 200px;
  height: 72vh;
}
</style>